﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MultiDAQ_Analysis.Util
{
    /// <summary>
    /// 测量结果基类
    /// </summary>
    public class MeasurementResult
    {
        public double AlphaActivity { get; set; }
        public double BetaActivity { get; set; }
        public string Unit { get; set; }
        public DateTime MeasurementTime { get; set; }
        public string MeasurementType { get; set; }
        public List<string> Warnings { get; set; } = new List<string>();
        public bool IsValid { get; set; } = true;
    }

    /// <summary>
    /// 工作源效率结果
    /// </summary>
    public class WorkingSourceEfficiencyResult
    {
        public double AlphaEfficiency { get; set; }        // ηe(α) %
        public double BetaEfficiency { get; set; }         // ηe(β) %
        public double AlphaEfficiencyRatio { get; set; }   // ηr(α) %
        public double BetaEfficiencyRatio { get; set; }    // ηr(β) %
        public double AlphaCrosstalk { get; set; }         // 串道比 %
        public double BetaCrosstalk { get; set; }          // 串道比 %
        public List<string> Warnings { get; set; } = new List<string>();
        public bool IsValid { get; set; } = true;
    }

    /// <summary>
    /// 标准源效率结果
    /// </summary>
    public class StandardSourceEfficiencyResult
    {
        public double AlphaEfficiency { get; set; }        // εs(α) %
        public double BetaEfficiency { get; set; }         // εs(β) %
        public List<string> Warnings { get; set; } = new List<string>();
        public bool IsValid { get; set; } = true;
    }

    /// <summary>
    /// 本底测量结果
    /// </summary>
    public class BackgroundMeasurementResult
    {
        public double AlphaCountRate { get; set; }         // α本底计数率 CPS
        public double BetaCountRate { get; set; }          // β本底计数率 CPS
        public double AlphaUncertainty { get; set; }       // α计数率不确定度 CPS
        public double BetaUncertainty { get; set; }        // β计数率不确定度 CPS
        public double AlphaRelativeError { get; set; }     // α相对误差 %
        public double BetaRelativeError { get; set; }      // β相对误差 %
        public int MeasurementCount { get; set; }          // 测量次数
        public double TotalMeasurementTime { get; set; }   // 总测量时间 s
        public List<string> Warnings { get; set; } = new List<string>();
        public bool IsValid { get; set; } = true;
        public DateTime MeasurementTime { get; set; } = DateTime.Now;

        // 原始数据记录
        public List<BackgroundMeasurement> RawMeasurements { get; set; } = new List<BackgroundMeasurement>();
    }

    /// <summary>
    /// 单次本底测量数据
    /// </summary>
    public class BackgroundMeasurement
    {
        public int AlphaCounts { get; set; }               // α总计数
        public int BetaCounts { get; set; }                // β总计数
        public double MeasurementTime { get; set; }        // 测量时间 s
        public double AlphaCountRate => AlphaCounts / MeasurementTime;  // α计数率
        public double BetaCountRate => BetaCounts / MeasurementTime;    // β计数率
        public DateTime Timestamp { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// αβ多通道检测系统计算器
    /// </summary>
    public class AlphaBetaCalculator
    {
        private const double MINUTES_TO_SECONDS = 60.0;
        private const double MG_TO_G = 0.001;
        private const double G_TO_KG = 0.001;
        private const double MG_TO_KG = 0.000001;

        /// <summary>
        /// 参数验证
        /// </summary>
        private void ValidateParameters(params (double value, string name, double min, double max)[] parameters)
        {
            foreach (var (value, name, min, max) in parameters)
            {
                if (value < min || value > max)
                {
                    throw new ArgumentOutOfRangeException(name, $"{name} 必须在 {min} 到 {max} 之间，当前值：{value}");
                }
            }
        }

        /// <summary>
        /// 单次本底测量计算
        /// </summary>
        /// <param name="alphaCounts">α通道总计数</param>
        /// <param name="betaCounts">β通道总计数</param>
        /// <param name="measurementTime">测量时间(秒)</param>
        /// <returns>本底测量结果</returns>
        public BackgroundMeasurementResult CalculateSingleBackground(
            int alphaCounts,
            int betaCounts,
            double measurementTime)
        {
            var result = new BackgroundMeasurementResult
            {
                MeasurementCount = 1,
                TotalMeasurementTime = measurementTime
            };

            try
            {
                // 参数验证
                if (measurementTime <= 0)
                    throw new ArgumentException("测量时间必须大于0");
                if (alphaCounts < 0 || betaCounts < 0)
                    throw new ArgumentException("计数不能为负数");

                // 添加原始数据
                result.RawMeasurements.Add(new BackgroundMeasurement
                {
                    AlphaCounts = alphaCounts,
                    BetaCounts = betaCounts,
                    MeasurementTime = measurementTime
                });

                // 计算本底计数率 (CPS)
                result.AlphaCountRate = alphaCounts / measurementTime;
                result.BetaCountRate = betaCounts / measurementTime;

                // 计算统计不确定度 (基于泊松统计)
                // 标准偏差 = √N, 计数率不确定度 = √N / t
                result.AlphaUncertainty = Math.Sqrt(alphaCounts) / measurementTime;
                result.BetaUncertainty = Math.Sqrt(betaCounts) / measurementTime;

                // 计算相对误差 (%)
                result.AlphaRelativeError = alphaCounts > 0 ? (result.AlphaUncertainty / result.AlphaCountRate) * 100 : 0;
                result.BetaRelativeError = betaCounts > 0 ? (result.BetaUncertainty / result.BetaCountRate) * 100 : 0;

                // 数据质量评估
                if (alphaCounts == 0) result.Warnings.Add("α通道未检测到计数");
                if (betaCounts == 0) result.Warnings.Add("β通道未检测到计数");
                if (result.AlphaRelativeError > 10) result.Warnings.Add($"α本底相对误差较大: {result.AlphaRelativeError:F1}%");
                if (result.BetaRelativeError > 10) result.Warnings.Add($"β本底相对误差较大: {result.BetaRelativeError:F1}%");
                if (measurementTime < 300) result.Warnings.Add("测量时间较短，建议延长测量时间以获得更好的统计精度");

                // 推荐的最小计数检查
                if (alphaCounts < 100) result.Warnings.Add("α计数偏少，建议延长测量时间");
                if (betaCounts < 100) result.Warnings.Add("β计数偏少，建议延长测量时间");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 多次本底测量统计分析
        /// </summary>
        /// <param name="measurements">多次测量数据</param>
        /// <returns>统计分析结果</returns>
        public BackgroundMeasurementResult CalculateMultipleBackground(
            List<BackgroundMeasurement> measurements)
        {
            var result = new BackgroundMeasurementResult
            {
                MeasurementCount = measurements.Count,
                RawMeasurements = new List<BackgroundMeasurement>(measurements)
            };

            try
            {
                if (measurements == null || measurements.Count == 0)
                    throw new ArgumentException("测量数据不能为空");

                // 计算总测量时间
                result.TotalMeasurementTime = measurements.Sum(m => m.MeasurementTime);

                // 计算加权平均计数率
                double totalAlphaCounts = measurements.Sum(m => (double)m.AlphaCounts);
                double totalBetaCounts = measurements.Sum(m => (double)m.BetaCounts);

                result.AlphaCountRate = totalAlphaCounts / result.TotalMeasurementTime;
                result.BetaCountRate = totalBetaCounts / result.TotalMeasurementTime;

                // 计算综合统计不确定度
                result.AlphaUncertainty = Math.Sqrt(totalAlphaCounts) / result.TotalMeasurementTime;
                result.BetaUncertainty = Math.Sqrt(totalBetaCounts) / result.TotalMeasurementTime;

                // 计算相对误差
                result.AlphaRelativeError = totalAlphaCounts > 0 ? (result.AlphaUncertainty / result.AlphaCountRate) * 100 : 0;
                result.BetaRelativeError = totalBetaCounts > 0 ? (result.BetaUncertainty / result.BetaCountRate) * 100 : 0;

                // 稳定性分析 - 计算各次测量的标准偏差
                var alphaRates = measurements.Select(m => m.AlphaCountRate).ToArray();
                var betaRates = measurements.Select(m => m.BetaCountRate).ToArray();

                double alphaStdDev = CalculateStandardDeviation(alphaRates);
                double betaStdDev = CalculateStandardDeviation(betaRates);

                // 期望的泊松标准偏差（理论值）
                double expectedAlphaStdDev = Math.Sqrt(result.AlphaCountRate / measurements.Average(m => m.MeasurementTime));
                double expectedBetaStdDev = Math.Sqrt(result.BetaCountRate / measurements.Average(m => m.MeasurementTime));

                // 数据质量评估
                if (measurements.Count < 3) result.Warnings.Add("测量次数较少，建议增加测量次数");
                if (result.AlphaRelativeError > 5) result.Warnings.Add($"α本底相对误差: {result.AlphaRelativeError:F1}%");
                if (result.BetaRelativeError > 5) result.Warnings.Add($"β本底相对误差: {result.BetaRelativeError:F1}%");

                // 稳定性检查 - 如果实测标准偏差明显大于理论值，说明系统不稳定
                if (alphaStdDev > expectedAlphaStdDev * 1.5)
                    result.Warnings.Add("α通道本底可能不稳定，建议检查测量条件");
                if (betaStdDev > expectedBetaStdDev * 1.5)
                    result.Warnings.Add("β通道本底可能不稳定，建议检查测量条件");

                // 异常值检测（简单的3σ规则）
                var alphaOutliers = DetectOutliers(alphaRates, 3.0);
                var betaOutliers = DetectOutliers(betaRates, 3.0);

                if (alphaOutliers.Any())
                    result.Warnings.Add($"α通道发现 {alphaOutliers.Count} 个异常值");
                if (betaOutliers.Any())
                    result.Warnings.Add($"β通道发现 {betaOutliers.Count} 个异常值");

                // 测量时间一致性检查
                var timeDifferences = measurements.Select(m => Math.Abs(m.MeasurementTime - measurements[0].MeasurementTime)).Max();
                if (timeDifferences > measurements[0].MeasurementTime * 0.1)
                    result.Warnings.Add("各次测量时间差异较大，可能影响统计分析");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 便捷方法：通过计数和时间数组计算多次本底
        /// </summary>
        public BackgroundMeasurementResult CalculateMultipleBackground(
            int[] alphaCounts,
            int[] betaCounts,
            double[] measurementTimes)
        {
            if (alphaCounts.Length != betaCounts.Length || alphaCounts.Length != measurementTimes.Length)
                throw new ArgumentException("数组长度必须相等");

            var measurements = new List<BackgroundMeasurement>();
            for (int i = 0; i < alphaCounts.Length; i++)
            {
                measurements.Add(new BackgroundMeasurement
                {
                    AlphaCounts = alphaCounts[i],
                    BetaCounts = betaCounts[i],
                    MeasurementTime = measurementTimes[i]
                });
            }

            return CalculateMultipleBackground(measurements);
        }

        /// <summary>
        /// 计算数组的标准偏差
        /// </summary>
        private double CalculateStandardDeviation(double[] values)
        {
            if (values.Length < 2) return 0;

            double mean = values.Average();
            double sumSquaredDiffs = values.Sum(x => Math.Pow(x - mean, 2));
            return Math.Sqrt(sumSquaredDiffs / (values.Length - 1));
        }

        /// <summary>
        /// 异常值检测（基于标准偏差）
        /// </summary>
        private List<int> DetectOutliers(double[] values, double threshold = 3.0)
        {
            var outliers = new List<int>();
            if (values.Length < 3) return outliers;

            double mean = values.Average();
            double stdDev = CalculateStandardDeviation(values);

            for (int i = 0; i < values.Length; i++)
            {
                if (Math.Abs(values[i] - mean) > threshold * stdDev)
                    outliers.Add(i);
            }

            return outliers;
        }

        /// <summary>
        /// 工作源效率测量计算
        /// </summary>
        public WorkingSourceEfficiencyResult CalculateWorkingSourceEfficiency(
            double alphaCountRate,      // Rs(α) 计数/min
            double betaCountRate,       // Rs(β) 计数/min
            double alphaBackground,     // Rb(α) 计数/min
            double betaBackground,      // Rb(β) 计数/min
            double alphaEmissionRate,   // I(α) 粒子/min
            double betaEmissionRate,    // I(β) 粒子/min
            double geometricFactor = 0.9) // G 几何因子
        {
            var result = new WorkingSourceEfficiencyResult();

            try
            {
                // 参数验证
                ValidateParameters(
                    (geometricFactor, nameof(geometricFactor), 0.1, 1.0),
                    (alphaCountRate, nameof(alphaCountRate), 0, double.MaxValue),
                    (betaCountRate, nameof(betaCountRate), 0, double.MaxValue)
                );

                // α工作源效率计算
                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                if (alphaEmissionRate > 0)
                {
                    result.AlphaEfficiency = (alphaNetCount / alphaEmissionRate) * 100.0;
                    result.AlphaEfficiencyRatio = (alphaNetCount / (alphaEmissionRate * geometricFactor)) * 100.0;
                }

                if (betaEmissionRate > 0)
                {
                    result.BetaEfficiency = (betaNetCount / betaEmissionRate) * 100.0;
                    result.BetaEfficiencyRatio = (betaNetCount / (betaEmissionRate * geometricFactor)) * 100.0;
                }

                // 串道比计算
                if (alphaCountRate > 0)
                    result.BetaCrosstalk = (betaCountRate / alphaCountRate) * 100.0;

                if (betaCountRate > 0)
                    result.AlphaCrosstalk = (alphaCountRate / betaCountRate) * 100.0;

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零，请检查本底扣除");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零，请检查本底扣除");
                if (result.AlphaEfficiency > 100) result.Warnings.Add("α效率超过100%，请检查参数");
                if (result.BetaEfficiency > 100) result.Warnings.Add("β效率超过100%，请检查参数");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 标准源效率测量计算
        /// </summary>
        public StandardSourceEfficiencyResult CalculateStandardSourceEfficiency(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            double alphaSpecificActivity = 12.5,  // As(α) Bq/g
            double betaSpecificActivity = 14.4,   // As(β) Bq/g
            double sourceMass = 200)    // Ms mg (默认0.1A mg，A=2000mm²)
        {
            var result = new StandardSourceEfficiencyResult();

            try
            {
                // 参数验证
                ValidateParameters(
                    (sourceMass, nameof(sourceMass), 1, 5000),
                    (alphaSpecificActivity, nameof(alphaSpecificActivity), 0, 1000),
                    (betaSpecificActivity, nameof(betaSpecificActivity), 0, 1000)
                );

                // 单位转换：mg → g
                double sourceMassInGrams = sourceMass * MG_TO_G;

                // α标准源效率计算
                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                if (alphaSpecificActivity > 0 && sourceMassInGrams > 0)
                {
                    // 公式：εs(α) = [Rs(α) - Rb(α)] / [As(α) × Ms(α)] × 1000 × 100%
                    // 1000是单位转换因子 (mg/g)
                    result.AlphaEfficiency = (alphaNetCount / (alphaSpecificActivity * sourceMassInGrams)) * 100.0;
                }

                if (betaSpecificActivity > 0 && sourceMassInGrams > 0)
                {
                    result.BetaEfficiency = (betaNetCount / (betaSpecificActivity * sourceMassInGrams)) * 100.0;
                }

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零，请检查本底扣除");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零，请检查本底扣除");
                if (result.AlphaEfficiency > 100) result.Warnings.Add("α效率超过100%，请检查参数");
                if (result.BetaEfficiency > 100) result.Warnings.Add("β效率超过100%，请检查参数");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 一般样品测量计算
        /// </summary>
        public MeasurementResult CalculateGeneralSample(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            bool useStandardEfficiency = true,
            double alphaEfficiency = 0.35,      // εs(α) 或 ηe(α) %
            double betaEfficiency = 0.3)        // εs(β) 或 ηe(β) %
        {
            var result = new MeasurementResult
            {
                MeasurementType = "一般样品",
                Unit = "Bq",
                MeasurementTime = DateTime.Now
            };

            try
            {
                // 参数验证
                ValidateParameters(
                    (alphaEfficiency, nameof(alphaEfficiency), 0.01, 100),
                    (betaEfficiency, nameof(betaEfficiency), 0.01, 100)
                );

                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                // 转换为小数形式
                double alphaEff = alphaEfficiency / 100.0;
                double betaEff = betaEfficiency / 100.0;

                // 活度计算：A = (Rs - Rb) / ε
                result.AlphaActivity = alphaNetCount / alphaEff;
                result.BetaActivity = betaNetCount / betaEff;

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零");

                string efficiencyType = useStandardEfficiency ? "标准源效率" : "工作源效率";
                result.Warnings.Add($"使用{efficiencyType}进行计算");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 水样品测量计算
        /// </summary>
        public MeasurementResult CalculateWaterSample(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            double waterVolume,         // V 水样体积 L
            double totalResidue,        // m 总残渣量 mg
            double measuredMass,        // mp 被测样品量 mg
            bool useStandardEfficiency = true,
            double alphaEfficiency = 0.35,      // εs(α) 或 ηe(α) %
            double betaEfficiency = 0.3)        // εs(β) 或 ηe(β) %
        {
            var result = new MeasurementResult
            {
                MeasurementType = "水样品",
                Unit = "Bq/L",
                MeasurementTime = DateTime.Now
            };

            try
            {
                // 参数验证
                ValidateParameters(
                    (waterVolume, nameof(waterVolume), 1, 99),
                    (totalResidue, nameof(totalResidue), 1, 9999),
                    (measuredMass, nameof(measuredMass), 1, 5000),
                    (alphaEfficiency, nameof(alphaEfficiency), 0.01, 100),
                    (betaEfficiency, nameof(betaEfficiency), 0.01, 100)
                );

                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                // 转换为小数形式
                double alphaEff = alphaEfficiency / 100.0;
                double betaEff = betaEfficiency / 100.0;

                // 浓度计算：C = (Rs - Rb) / ε × (m / (mp × V))
                result.AlphaActivity = (alphaNetCount / alphaEff) * (totalResidue / (measuredMass * waterVolume));
                result.BetaActivity = (betaNetCount / betaEff) * (totalResidue / (measuredMass * waterVolume));

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零");
                if (totalResidue < measuredMass) result.Warnings.Add("总残渣量小于被测样品量，请检查");

                string efficiencyType = useStandardEfficiency ? "标准源效率" : "工作源效率";
                result.Warnings.Add($"使用{efficiencyType}进行计算");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 生物样品测量计算
        /// </summary>
        public MeasurementResult CalculateBiologicalSample(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            double freshWeight,         // w 鲜样重量 kg
            double totalAsh,            // m 样品总灰量 mg
            double measuredMass,        // mp 样品源质量 mg
            double recoveryRate,        // Y 回收率 (≤1)
            bool useStandardEfficiency = true,
            double alphaEfficiency = 0.35,      // εs(α) 或 ηe(α) %
            double betaEfficiency = 0.3)        // εs(β) 或 ηe(β) %
        {
            var result = new MeasurementResult
            {
                MeasurementType = "生物样品",
                Unit = "Bq/kg",
                MeasurementTime = DateTime.Now
            };

            try
            {
                // 参数验证
                ValidateParameters(
                    (freshWeight, nameof(freshWeight), 1, 49),
                    (totalAsh, nameof(totalAsh), 1, 1000000),
                    (measuredMass, nameof(measuredMass), 1, 5000),
                    (recoveryRate, nameof(recoveryRate), 0.01, 1.0),
                    (alphaEfficiency, nameof(alphaEfficiency), 0.01, 100),
                    (betaEfficiency, nameof(betaEfficiency), 0.01, 100)
                );

                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                // 转换为小数形式
                double alphaEff = alphaEfficiency / 100.0;
                double betaEff = betaEfficiency / 100.0;

                // 浓度计算：C = (Rs - Rb) / ε × m / (mp × Y × w)
                result.AlphaActivity = (alphaNetCount / alphaEff) * (totalAsh / (measuredMass * recoveryRate * freshWeight));
                result.BetaActivity = (betaNetCount / betaEff) * (totalAsh / (measuredMass * recoveryRate * freshWeight));

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零");
                if (totalAsh < measuredMass) result.Warnings.Add("总灰量小于被测样品量，请检查");
                if (recoveryRate > 1.0) result.Warnings.Add("回收率不能大于1");

                string efficiencyType = useStandardEfficiency ? "标准源效率" : "工作源效率";
                result.Warnings.Add($"使用{efficiencyType}进行计算");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 气体样品测量计算
        /// </summary>
        public MeasurementResult CalculateGasSample(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            double samplingVolume,      // V 采样体积 L
            double filterEfficiency,    // η 过滤效率 % (1-100)
            double absorptionCoeff,     // F 吸收系数 % (1-100)
            bool useStandardEfficiency = true,
            double alphaEfficiency = 0.35,      // εs(α) 或 ηe(α) %
            double betaEfficiency = 0.3)        // εs(β) 或 ηe(β) %
        {
            var result = new MeasurementResult
            {
                MeasurementType = "气体样品",
                Unit = "Bq/L",
                MeasurementTime = DateTime.Now
            };

            try
            {
                // 参数验证
                ValidateParameters(
                    (samplingVolume, nameof(samplingVolume), 1, 1000000),
                    (filterEfficiency, nameof(filterEfficiency), 1, 100),
                    (absorptionCoeff, nameof(absorptionCoeff), 1, 100),
                    (alphaEfficiency, nameof(alphaEfficiency), 0.01, 100),
                    (betaEfficiency, nameof(betaEfficiency), 0.01, 100)
                );

                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                // 转换为小数形式
                double alphaEff = alphaEfficiency / 100.0;
                double betaEff = betaEfficiency / 100.0;
                double filterEff = filterEfficiency / 100.0;
                double absorpCoeff = absorptionCoeff / 100.0;

                // 浓度计算：C = (Rs - Rb) / (V × ε × η × F)
                result.AlphaActivity = alphaNetCount / (samplingVolume * alphaEff * filterEff * absorpCoeff);
                result.BetaActivity = betaNetCount / (samplingVolume * betaEff * filterEff * absorpCoeff);

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零");
                if (filterEfficiency < 50) result.Warnings.Add("过滤效率较低，可能影响测量精度");
                if (absorptionCoeff < 50) result.Warnings.Add("吸收系数较低，可能影响测量精度");

                string efficiencyType = useStandardEfficiency ? "标准源效率" : "工作源效率";
                result.Warnings.Add($"使用{efficiencyType}进行计算");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 环境样品测量计算
        /// </summary>
        public MeasurementResult CalculateEnvironmentalSample(
            double alphaCountRate,      // Rs(α) 计数/s
            double betaCountRate,       // Rs(β) 计数/s
            double alphaBackground,     // Rb(α) 计数/s
            double betaBackground,      // Rb(β) 计数/s
            double sampleMass,          // mp 样品质量 mg
            double correctionFactor = 1.0,  // K 校正系数
            bool useStandardEfficiency = true,
            double alphaEfficiency = 0.35,      // εs(α) 或 ηe(α) %
            double betaEfficiency = 0.3)        // εs(β) 或 ηe(β) %
        {
            var result = new MeasurementResult
            {
                MeasurementType = "环境样品",
                Unit = "Bq/kg",
                MeasurementTime = DateTime.Now
            };

            try
            {
                // 参数验证
                ValidateParameters(
                    (sampleMass, nameof(sampleMass), 1, 5000),
                    (correctionFactor, nameof(correctionFactor), 0.1, 10),
                    (alphaEfficiency, nameof(alphaEfficiency), 0.01, 100),
                    (betaEfficiency, nameof(betaEfficiency), 0.01, 100)
                );

                double alphaNetCount = alphaCountRate - alphaBackground;
                double betaNetCount = betaCountRate - betaBackground;

                // 转换为小数形式
                double alphaEff = alphaEfficiency / 100.0;
                double betaEff = betaEfficiency / 100.0;

                // 浓度计算：C = K × [(Rs - Rb) × 10⁶] / [ε × mp]
                // 10⁶ 是 mg 转 kg 的转换因子
                result.AlphaActivity = correctionFactor * (alphaNetCount * 1000000) / (alphaEff * sampleMass);
                result.BetaActivity = correctionFactor * (betaNetCount * 1000000) / (betaEff * sampleMass);

                // 警告检查
                if (alphaNetCount <= 0) result.Warnings.Add("α净计数为负或零");
                if (betaNetCount <= 0) result.Warnings.Add("β净计数为负或零");
                if (Math.Abs(correctionFactor - 1.0) > 0.1) result.Warnings.Add($"使用了校正系数：{correctionFactor}");

                string efficiencyType = useStandardEfficiency ? "标准源效率" : "工作源效率";
                result.Warnings.Add($"使用{efficiencyType}进行计算");
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Warnings.Add($"计算错误：{ex.Message}");
            }

            return result;
        }
    }

    /// <summary>
    /// 使用示例和测试类
    /// </summary>
    //public class Program
    //{
    //    public static void Main(string[] args)
    //    {
    //        var calculator = new AlphaBetaCalculator();

    //        Console.WriteLine("=== αβ多通道检测系统计算工具演示 ===\n");

    //        // 0. 本底测量示例
    //        Console.WriteLine("0. 本底测量计算:");

    //        // 单次本底测量
    //        Console.WriteLine("  单次本底测量:");
    //        var singleBackground = calculator.CalculateSingleBackground(
    //            alphaCounts: 125,     // α通道总计数
    //            betaCounts: 98,       // β通道总计数
    //            measurementTime: 300  // 测量时间 300秒
    //        );

    //        Console.WriteLine($"    α本底计数率: {singleBackground.AlphaCountRate:F4} ± {singleBackground.AlphaUncertainty:F4} CPS");
    //        Console.WriteLine($"    β本底计数率: {singleBackground.BetaCountRate:F4} ± {singleBackground.BetaUncertainty:F4} CPS");
    //        Console.WriteLine($"    α相对误差: {singleBackground.AlphaRelativeError:F1}%");
    //        Console.WriteLine($"    β相对误差: {singleBackground.BetaRelativeError:F1}%");

    //        // 多次本底测量
    //        Console.WriteLine("\n  多次本底测量统计:");
    //        var multipleBackground = calculator.CalculateMultipleBackground(
    //            alphaCounts: new int[] { 125, 118, 132, 121, 129 },  // 5次α测量
    //            betaCounts: new int[] { 98, 105, 91, 102, 96 },      // 5次β测量
    //            measurementTimes: new double[] { 300, 300, 300, 300, 300 } // 每次300秒
    //        );

    //        Console.WriteLine($"    测量次数: {multipleBackground.MeasurementCount}");
    //        Console.WriteLine($"    总测量时间: {multipleBackground.TotalMeasurementTime}秒");
    //        Console.WriteLine($"    α平均本底: {multipleBackground.AlphaCountRate:F4} ± {multipleBackground.AlphaUncertainty:F4} CPS");
    //        Console.WriteLine($"    β平均本底: {multipleBackground.BetaCountRate:F4} ± {multipleBackground.BetaUncertainty:F4} CPS");
    //        Console.WriteLine($"    α相对误差: {multipleBackground.AlphaRelativeError:F1}%");
    //        Console.WriteLine($"    β相对误差: {multipleBackground.BetaRelativeError:F1}%");

    //        if (multipleBackground.Warnings.Count > 0)
    //        {
    //            Console.WriteLine("    警告信息:");
    //            foreach (var warning in multipleBackground.Warnings)
    //                Console.WriteLine($"      - {warning}");
    //        }
    //        Console.WriteLine();

    //        // 1. 工作源效率测量示例
    //        Console.WriteLine("1. 工作源效率测量:");
    //        var workingEff = calculator.CalculateWorkingSourceEfficiency(
    //            alphaCountRate: 1440,     // α计数率
    //            betaCountRate: 1594,      // β计数率  
    //            alphaBackground: multipleBackground.AlphaCountRate * 60, // 转换为 min⁻¹
    //            betaBackground: multipleBackground.BetaCountRate * 60,   // 转换为 min⁻¹
    //            alphaEmissionRate: 4140,  // α发射率
    //            betaEmissionRate: 5320    // β发射率
    //        );

    //        Console.WriteLine($"  α效率: {workingEff.AlphaEfficiency:F2}%");
    //        Console.WriteLine($"  β效率: {workingEff.BetaEfficiency:F2}%");
    //        Console.WriteLine($"  α串道比: {workingEff.AlphaCrosstalk:F2}%");
    //        Console.WriteLine($"  β串道比: {workingEff.BetaCrosstalk:F2}%\n");

    //        // 2. 标准源效率测量示例
    //        Console.WriteLine("2. 标准源效率测量:");
    //        var standardEff = calculator.CalculateStandardSourceEfficiency(
    //            alphaCountRate: 5.0,      // α计数率 s⁻¹
    //            betaCountRate: 4.3,       // β计数率 s⁻¹
    //            alphaBackground: multipleBackground.AlphaCountRate,   // 使用实测本底
    //            betaBackground: multipleBackground.BetaCountRate,     // 使用实测本底
    //            sourceMass: 20            // 源质量 mg
    //        );

    //        Console.WriteLine($"  α标准源效率: {standardEff.AlphaEfficiency:F3}%");
    //        Console.WriteLine($"  β标准源效率: {standardEff.BetaEfficiency:F3}%\n");

    //        // 3. 水样品测量示例
    //        Console.WriteLine("3. 水样品测量:");
    //        var waterResult = calculator.CalculateWaterSample(
    //            alphaCountRate: 0.5,      // α计数率 s⁻¹
    //            betaCountRate: 1.2,       // β计数率 s⁻¹
    //            alphaBackground: multipleBackground.AlphaCountRate,   // 使用实测本底
    //            betaBackground: multipleBackground.BetaCountRate,     // 使用实测本底
    //            waterVolume: 20,          // 水样体积 L
    //            totalResidue: 100,        // 总残渣 mg
    //            measuredMass: 30,         // 被测样品量 mg
    //            alphaEfficiency: standardEff.AlphaEfficiency,
    //            betaEfficiency: standardEff.BetaEfficiency
    //        );

    //        Console.WriteLine($"  总α活度浓度: {waterResult.AlphaActivity:F3} {waterResult.Unit}");
    //        Console.WriteLine($"  总β活度浓度: {waterResult.BetaActivity:F3} {waterResult.Unit}");
    //        if (waterResult.Warnings.Count > 0)
    //        {
    //            Console.WriteLine("  警告信息:");
    //            foreach (var warning in waterResult.Warnings)
    //                Console.WriteLine($"    - {warning}");
    //        }

    //        Console.WriteLine("\n=== 本底测量详细数据 ===");
    //        Console.WriteLine("各次测量详情:");
    //        for (int i = 0; i < multipleBackground.RawMeasurements.Count; i++)
    //        {
    //            var measurement = multipleBackground.RawMeasurements[i];
    //            Console.WriteLine($"  第{i + 1}次: α={measurement.AlphaCounts}计数({measurement.AlphaCountRate:F4}CPS), " +
    //                            $"β={measurement.BetaCounts}计数({measurement.BetaCountRate:F4}CPS), " +
    //                            $"时间={measurement.MeasurementTime}s");
    //        }
    //    }
    //}
}